import { getServiceTaskLikeBusinessObject } from './bpmnPropertyUtils/eventDefinition'
import { getExtensionElementsList, createModdleElement, addExtensionElements, removeExtensionElements } from './bpmnPropertyUtils/extensionElements'
import { useSettingStore } from '@/store/bpmnProcess/settingStore'

export function isFieldInjectionsSupported(element) {
  return getServiceTaskLikeBusinessObject(element)
}

export function getFieldInjections(element) {
  const prefix = useSettingStore().editor.processEngine
  const businessObject = getServiceTaskLikeBusinessObject(element)
  return getExtensionElementsList(businessObject, `${prefix}:Field`)
}

export function addFieldInjection(element, field) {
  const prefix = useSettingStore().editor.processEngine
  const businessObject = getServiceTaskLikeBusinessObject(element)
  const { name, fieldType, string, expression } = field
  const fieldConfig = fieldType === 'string' ? { name, string } : { name, expression }
  const fieldInjection = createModdleElement(`${prefix}:Field`, fieldConfig, null)
  addExtensionElements(element, businessObject, fieldInjection)
}

export function editFieldInjection(element, field, oldField) {
  removeFieldInjection(element, oldField)
  addFieldInjection(element, field)
}

export function removeFieldInjection(element, field) {
  const businessObject = getServiceTaskLikeBusinessObject(element)
  removeExtensionElements(element, businessObject, field)
}

export function determineType(field) {
  // string is the default type
  return ('string' in field && 'string') || ('expression' in field && 'expression') || ('stringValue' in field && 'string') || 'string'
}
export function getValue(field) {
  // string is the default type
  return field.string || field.stringValue || field.expression
}
